package com.lee.database;

import com.lee.logger.Logger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;

import java.io.IOException;
import java.io.Serializable;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class HBaseConnPool implements Serializable {
    private static Configuration conf = null;
    private static Connection conn = null;
    private static final HBaseConnPool instance = new HBaseConnPool();
    private HBaseConnPool(){
        Logger.debug("init HBaseConnPool");
    }
    public static HBaseConnPool getInstance(){
        Logger.debug("get HBase instance");
        if(instance == null){
            Logger.error("get instance error, instance is null.");
        }
        return instance;
    }
    public synchronized  Connection getConnection() throws IOException {
        Logger.debug("get connection");
        if(conn == null || conn.isClosed()){
            Logger.debug("recreate HBase connection");
            closeConnectionPool();
            createConnectionPool();
        }
        if(conn == null){
            Logger.error("get connection error, conn is null");

        }
        return conn;
    }
    private void createConnectionPool() throws IOException {
        Logger.debug("create connection pool");
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","localhost");
        conf.set("hbase.zookeeper.property.clientPort","2181");
        conn = ConnectionFactory.createConnection(conf);
        Logger.debug("create connection pool success");

    }
    private void closeConnectionPool() throws IOException {
        Logger.debug("close connection pool");
        if(conn == null){
            Logger.error("conn is null, end close");
            return;
        }
        conn.close();
        Logger.debug("end close");
    }

}